package com.tiantian.novel.resolver;

import com.tiantian.novel.model.ChapterInfo;
import com.tiantian.novel.model.NovelSummary;
import com.tiantian.novel.resolver.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 小说解析器
 *
 * @author wangk21
 * @date 2023/11/12.
 */
@Slf4j
@Service
public class NovelResolverProxy implements NovelResolver, InitializingBean {
    private Map<String, NovelResolver> resolverMap = new HashMap<>();

    @Override
    public NovelSummary resolveNovelSummary(String url) throws Exception {
        return getResolve(url).resolveNovelSummary(url);
    }

    @Override
    public ChapterInfo resovleChapter(String url) throws Exception {
        return getResolve(url).resovleChapter(url);
    }

    @Override
    public byte[] getImage(String url) throws IOException {
        return getResolve(url).getImage(url);
    }

    private NovelResolver getResolve(String url) {
        String key;
        if (url.startsWith("http")) {
            if (url.indexOf("blog.sina.com.cn") > -1) {
                key = "sinablog";
            } else if (url.indexOf("kline8.com") > -1) {
                key = "kline8";
            } else if (url.indexOf("book_") > -1) {
                key = "biqugeNew";
            } else {
                key = "biquge";
            }
        } else {
            key = "txt";
        }

        return resolverMap.get(key);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        resolverMap.put("biqugeNew", new BiqugeNewNovelResolver());
        resolverMap.put("biquge", new BiqugeNovelResolver());
        resolverMap.put("txt", new TxtNovelResolver());
        resolverMap.put("sinablog", new SinaBlogNovelResolver());
        resolverMap.put("kline8", new Kline8RovelResolver());
    }
}
